import axios from 'axios'
import { getToken, removeToken } from "@/utils/token"
import router from '@/router/index.js';
import { failed } from '@/utils/messageUtils.js';

const httpRequest = axios.create({
    baseURL: "/api",
    timeout: 60000,//设置最大响应时间,左边设置的是60s,即1min。
})

httpRequest.interceptors.request.use(function (config) {
    // 登录、请求验证码不需要携带token
    var currentUrl = config.url
    if(currentUrl != '/login' && currentUrl != '/captcha'){
        var token = getToken();
        // 请求头标志为token
        config.headers.token = token
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

/**
 * 响应拦截器，处理错误信息
 */
httpRequest.interceptors.response.use(function (response) {
    if(response.data.code == 500){ //业务异常
        failed(response.data.message)
    }else if(response.data.code == 4011){ //用户未登录
        failed(response.data.message)
        router.push("/login");
    }else if(response.data.code == 4012){ //token已过期
        failed(response.data.message)
        removeToken();
        router.push("/login");
    }else if(response.data.code == 4013){ //token非法
        failed(response.data.message)
        removeToken();
        router.push("/login");
    }else if(response.data.code == 401){ // 用户未授权
        failed(response.data.message)
        router.push("/401");
    }else if(response.data.code == 200){
        
    }else{
        failed("未知异常"+response.data.message)
    }
    return response.data;
}, function (error) {
    failed(error.message)
    return Promise.reject(error);
});



export default httpRequest